<template>
  <div class="machineMaintainProject-detail">
    <n-card v-if="loading" :bordered="false" class="proCard">
      <n-spin :show="loading" class="loading" />
    </n-card>

    <DFPageDetail v-else :page-options="pageOptions" />
  </div>
</template>

<script lang="ts" setup name="MachineMaintainProject">
  import lang from '../lang';

  import { useMixins } from '@/hooks/useMixins';

  import { generateRandomValue } from '@/utils/index';

  import {
    addMachineMaintainProject,
    updateMachineMaintainProject,
    // getListMachineMaintainProject,
    infoMachineMaintainProject,
  } from '@/api/base/machineMaintainProject';
  import { pageMaintainProject } from '@/api/base/maintainProject';
  import { listMachine } from '@/api/base/machine';

  const {
    t,
    loadLangFn,
    getDictDataListFn,
    routerType,
    message,
    // language
  } = useMixins();

  // 设备名称列表
  const machineList: any = ref([]);

  const projectNameList: any = ref([]);

  const maintenanceTypeList = ref([]);

  const loading = ref(false);

  loadLangFn(lang);

  // 获取设备名称
  const getMachineNameFn = async () => {
    const res = await Promise.all([listMachine()]);
    const [list1] = res;

    machineList.value =
      list1?.data.map((item) => ({
        label: item.machineName,
        value: item.machineCode,
        machineModel: item.machineModel,
      })) || [];
  };
  getMachineNameFn();

  //   获取项目名称
  //   获取保养类型
  async function getMachineMaintainDataFn() {
    try {
      const list = (await getDictDataListFn('maintenance_period_type')) || [];

      const data = await pageMaintainProject({
        entity: {
          maintainProjectCode: '',
          maintainProjectName: '',
        },
        pageNum: 1,
        pageSize: 9999,
      });
      maintenanceTypeList.value = list;

      projectNameList.value =
        data?.data?.list.map((project) => ({
          value: project.maintainProjectCode,
          label: project.maintainProjectName,
        })) || [];
    } catch (e) {
      console.log(e);
    }
  }

  const handleEditDataFn = (res: any = {}) => {
    if (res) {
      const { data } = res;
      if (routerType === 'copy') {
        delete data.id;
        delete data.machineName;
        delete data.machineCode;
        delete data.machineModel;
        if (data.machineMaintainProjectList && data.machineMaintainProjectList.length) {
          for (const item of data.machineMaintainProjectList) {
            delete item.id;
          }
        }
      }
      return data;
    }
  };

  const tableColumns = [
    // 项目名称
    {
      label: 'maintainProjectName',
      prop: 'maintainProjectCode',
      checkProp: 'maintainProjectName',
      required: true,
      itemData: {
        component: 'NSelect',
        options: projectNameList,
        componentProps: {
          tag: true,
          'on-create': (label: string) => {
            const maintainProjectCode = generateRandomValue(16);
            return { label, value:maintainProjectCode };
          },
          onUpdateValue: (_v: string, option: any, updateFormModelFn: any) => {
            if (updateFormModelFn && option) {
              const { value = null, label = null } = option;

              const data: any = {
                maintainProjectName: label,
                maintainProjectCode: value,
              };

              typeof updateFormModelFn === 'function' && updateFormModelFn(data);
            } else {
              typeof updateFormModelFn === 'function' &&
                updateFormModelFn({
                  maintainProjectName: null,
                  maintainProjectCode: null,
                });
            }
          },
        },
      },
    },
    {
      label:'maintainProjectCode'
    },
    // 单元
    {
      label: 'unit',
      required: true,
      itemData: {
        maxlength: 100,
      },
    },
    // 部位
    {
      label: 'part',
      required: true,
      itemData: {
        maxlength: 100,
      },
    },
    // 保养类型
    {
      label: 'periodRateName',
      prop: 'periodRateCode',
      checkProp: 'periodRateName',
      required: true,
      itemData: {
        component: 'NSelect',
        options: maintenanceTypeList,
        componentProps: {
          onUpdateValue: (_v: string, option: any, updateFormModelFn: any) => {
            if (updateFormModelFn && option) {
              const { value = null, label = null } = option;

              const data: any = {
                periodRateName: label,
                periodRateCode: value,
              };

              typeof updateFormModelFn === 'function' && updateFormModelFn(data);
            } else {
              typeof updateFormModelFn === 'function' &&
                updateFormModelFn({
                  periodRateName: null,
                  periodRateCode: null,
                });
            }
          },
        },
      },
    },
    // 保养周期（天）
    {
      label: 'periodRate',
      required: true,
      itemData: {
        maxlength: 100,
        component: 'NInputNumber',
        componentProps: {
          maxlength: 50,
          min: 1,
          precision: 0,
          clearable: true,
          showButton: false,
        },
      },
    },
    // 备注
    {
      label: 'remark',
      common: true,
      itemData: {
        maxlength: 100,
      },
    },
    // 附件
    {
      label: 'fileName',
      prop: 'fileUrl',
      ellipsis: false,
      itemData: {
        component: 'UploadImage',
        componentProps: {
          onUpdateValue(obj, updateFormModelFn) {
            // console.log(obj, 'obj');

            if (updateFormModelFn) {
              updateFormModelFn({ fileUrl: obj?.fileUrl, fileName: obj?.fileName });
            }
          },
        },
      },
    },
  ];

  const initFn = async () => {
    try {
      if (routerType !== 'check') {
        loading.value = true;
        // 获取项目名称
        // 获取保养类型
        getMachineMaintainDataFn();

        loading.value = false;

        // setTimeout(() => {
        //   loading.value = false;
        // }, 000);
      }
    } catch (e) {
      console.log(e);
    }
  };

  const checkSubmitFn = (editTableData = []) => {
    // 新增前校验规则
    // 1.同一个设备只能存在一条记录，重复添加时提示：“设备保养记录已存在”
    // 2.同一个项目只能维护一条相同保养类型的记录，若有多条，则提示“有相同保养项目与保养类型”
    // 3.同一个项目可维护多条不同保养类型的记录
    let isSubmit = true;
    if (editTableData && editTableData.length) {
      isSubmit =
        editTableData.filter((item) => {
          return editTableData.some(
            (otherItem) =>
              otherItem.maintainProjectCode === item.maintainProjectCode &&
              otherItem !== item &&
              otherItem.periodRateName === item.periodRateName
          );
        }).length === 0;
    }
    if (!isSubmit) {
      message.error(`${t('machineMaintainProject.tipMsg.submitErr1')}`);
    }

    return isSubmit;
  };

  const beforeSubmitFn = (data: any = {}, _refData: any = {}) => {
    const { machineMaintainProjectList = [] } = data;

    return checkSubmitFn(machineMaintainProjectList);
  };

  const pageOptions = {
    list: [
      {
        type: 'form',
        formSchemas: [
          // 设备名称
          {
            label: 'machineName',
            prop: 'machineName',
            checkProp: 'machineName',
            editDisabled: true,
            component: 'NSelect',
            options: machineList,
            required: true,
            componentProps: {
              onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                if (option) {
                  if (typeof updateFormModelFn === 'function') {
                    const { label, value, machineModel } = option;
                    updateFormModelFn({
                      machineCode: value,
                      machineName: label,
                      machineModel,
                    });
                  }
                } else {
                  typeof updateFormModelFn === 'function' &&
                    updateFormModelFn({
                      machineCode: null,
                      machineName: null,
                      machineModel: null,
                    });
                }
              },
            },
          },
          //   设备编码
          {
            label: 'machineCode',
            prop: 'machineCode',
            checkProp: 'machineCode',
            common: true,
            disabled: true,
            component: 'NInput',
          },
          //   设备型号
          {
            label: 'machineModel',
            prop: 'machineModel',
            disabled: true,
            component: 'NInput',
          },
          {
            label: 'remark',
            type: 'textarea',
            common: true,
            giProps: { span: 3 },
            componentProps: {
              'show-count': true,
            },
          },
        ],
      },
      {
        title: t('machineMaintainProject.table.tableName'),
        type: 'table',
        hasSelection: true,
        ref: 'machineMaintainProjectList',
        columns: tableColumns,
      },
    ],
    formLabelWidthEn: 100,
    descriptionsListLabelWidthEn: 150,
    routeName: 'machineMaintainProject',
    addDataFn: addMachineMaintainProject,
    updateDataFn: updateMachineMaintainProject,
    getDataFn: infoMachineMaintainProject,
    beforeSubmitFn,
    handleEditDataFn,
  };

  initFn();
</script>

<style lang="less" scoped>
  .standardProgramme-detail {
    position: relative;
    .loading {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
</style>
